import requests
# from urllib.parse import urlencode
# from pyquery import PyQuery as pq
import os
from multiprocessing.pool import Pool

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36'
}
baseUrl = 'https://www.toutiao.com'


def get_data(offset):
    '''
    :param offset: 0, 20, 40, ...
    :return: 正常就返回 json, 如果异常则返回 None
    '''
    params = {
        'offset': offset,
        'format': 'json',
        'keyword': '美女',
        'autoload': 'true',
        'count': 20,
        'cur_tab': 3,
        'from': 'gallery'
    }
    url = 'https://www.toutiao.com/search_content/'
    try:
        resp = requests.get(url, params = params, headers = headers)
        if resp.status_code == 200:
            # 返回 json 数据用 resp.json()
            return resp.json()
    except requests.ConnectionError as e:
        print(e)
        return None


def get_image(json):
    '''
    解析 json 数据
    :param json:
    :return:  yield 方式返回 title, image_url 的字典
    '''
    if json.get('data'):
        for item in json.get('data'):
            # 每个 item 就是一栏美女图 json 数据
            title = item.get('title') # 标题
            image_list = item.get('image_list')
            if image_list: # 注意检查空
                for image in image_list:
                    if image: # 注意检查空
                        yield {
                            'title': title,
                            'image_url': 'https:' + image.get('url')
                        }


def save_image(item):
    '''
    下载图片, 保存到 title 目录
    :param item:
    :return:
    '''
    # 新建目录
    title = item.get('title')
    url = item.get('image_url')
    image_name = url.split('/')[-1]

    if not os.path.exists(title):
        os.mkdir(title)
    try:
        resp = requests.get(url, headers = headers)
        if resp.status_code == 200:
            file_path = '{0}/{1}.{2}'.format(title, image_name, 'jpg')
            if not os.path.exists(file_path):
                with open(file_path, 'wb') as f:
                    f.write(resp.content)
            else:
                print('已经下载过了', file_path)
    except requests.ConnectionError as e:
        print('保存图片', image_name, '失败!')


def main(offset):
    json = get_data(offset)
    for item in get_image(json):
        print(item)
        save_image(item)


GROUP_START = 1
GROUP_END = 20

if __name__ == '__main__':
    pool = Pool()
    groups = ([x * 20 for x in range(GROUP_START, GROUP_END + 1)])
    pool.map(main, groups)
    pool.close()
    pool.join()
